package com.elitel.frame.base.service.impl;

import com.elitel.frame.base.service.BaseQueryfieldcacheService;
import com.elitel.frame.main.dao.BaseQueryfieldcacheMapper;
import com.elitel.frame.main.dao.CfgExtendMapper;
import com.elitel.frame.main.dao.ext.ExtBaseQueryfieldMapper;
import com.elitel.frame.main.dao.ext.ExtBaseQueryfieldcacheMapper;
import com.elitel.frame.main.dao.ext.ExtCfgTableMapper;
import com.elitel.frame.main.dao.ext.ExtSysFunctionMapper;
import com.elitel.frame.main.entity.*;
import com.elitel.frame.main.entity.ext.BaseQueryfieldcacheExt;
import com.elitel.frame.main.entity.ext.SysFunctionExt;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class BaseQueryfieldcacheServiceImpl implements BaseQueryfieldcacheService {

    @Autowired
    private ExtBaseQueryfieldcacheMapper extbaseQueryfieldcacheMapper;
    @Autowired
    private BaseQueryfieldcacheMapper baseQueryfieldcacheMapper;
    @Autowired
    private ExtBaseQueryfieldMapper extBaseQueryfieldMapper;
    @Autowired
    private ExtSysFunctionMapper extSysFunctionMapper;
    @Autowired
    private CfgExtendMapper cfgExtendMapper;
    @Autowired
    private ExtCfgTableMapper extCfgTableMapper;


    @Override
    public List<BaseQueryfieldcacheExt> queryCacheFieldGroup(String serviceid, String servicetype) {
        List<BaseQueryfieldcacheExt> list = extbaseQueryfieldcacheMapper.queryCacheFieldByService(serviceid, servicetype);
        List<BaseQueryfieldcacheExt> dataList = removeDuplicateOrder(list);
        return dataList;
    }

    //查询缓存条件组(如果serviceId serviceType groupId均为空 则查询所有的) 组概念 以组为单位
    @Override
    public List<BaseQueryfieldcacheExt> queryAllFieldCacheGroup(String serviceId, String serviceType, String groupId) {
        List<BaseQueryfieldcacheExt> list = extbaseQueryfieldcacheMapper.queryAllFieldCacheGroup(serviceId, serviceType, groupId);
        List<BaseQueryfieldcacheExt> dataList = removeDuplicateOrder(list);
        return dataList;
    }

    @Override
    public List<BaseQueryfieldcacheExt> queryCacheFieldByServiceIdGroupId(String serviceid, String servicetype, String parametergroup) {
        List<BaseQueryfieldcacheExt> list = null;
        if (servicetype.equals("singleTableServer")) {
            CfgExtend cfgExtend = cfgExtendMapper.selectByPrimaryKey(serviceid);
            CfgTable cfgTable = extCfgTableMapper.getInfoByDtconfigId(cfgExtend.getDtConfigId());
            if(cfgTable.getDtTabletype().equals(1)){
                //数据表
                list = extbaseQueryfieldcacheMapper.queryCacheFieldByServiceIdGroupId(serviceid, servicetype, parametergroup);
            } else if(cfgTable.getDtTabletype().equals(2)){
                //视图
                list = extbaseQueryfieldcacheMapper.queryCacheFieldByServiceIdGroupIdtoView(serviceid, servicetype, parametergroup);
            }

        }

        return list;
    }

    @Override
    public Integer addQueryFieldCacheList(List<BaseQueryfieldcache> list) {
        Integer size = 0;
        if (list == null || list.size() <= 0)
            return size;
        for (BaseQueryfieldcache fieldcache : list) {
            fieldcache.setGuid(UUID.randomUUID().toString());
            size += baseQueryfieldcacheMapper.insertSelective(fieldcache);
        }
        return size;
    }

    @Override
    public Integer deleteQueryFieldCacheList(String serviceid, String parametergroup) {
        Integer size = 0;
        size += extbaseQueryfieldcacheMapper.deleteQueryFieldCacheListByServiceIdGroup(serviceid, parametergroup);
        return size;
    }

    @Override
    public Integer updateQueryFieldCacheList(List<BaseQueryfieldcache> list) {
        Integer size = 0;
        if (list == null || list.size() <= 0)
            return size;
        for (BaseQueryfieldcache fieldcache : list) {
            size += baseQueryfieldcacheMapper.updateByPrimaryKeySelective(fieldcache);
        }
        return size;
    }

    /**
     * 去重
     *
     * @param orderList
     * @return
     */
    private static List<BaseQueryfieldcacheExt> removeDuplicateOrder(List<BaseQueryfieldcacheExt> orderList) {
        Set<BaseQueryfieldcacheExt> set = new TreeSet<BaseQueryfieldcacheExt>(new Comparator<BaseQueryfieldcacheExt>() {
            @Override
            public int compare(BaseQueryfieldcacheExt a, BaseQueryfieldcacheExt b) {
                // 字符串则按照asicc码升序排列
                return a.getParametergroup().compareTo(b.getParametergroup());
            }
        });

        set.addAll(orderList);
        return new ArrayList<BaseQueryfieldcacheExt>(set);
    }

    @Override
    public BaseQueryfieldcacheExt getQueryFieldCacheByGuid(String guid) {
        BaseQueryfieldcacheExt baseQueryfieldcacheExt = extbaseQueryfieldcacheMapper.getQueryFieldCacheByGuid(guid);
        return baseQueryfieldcacheExt;
    }

    /**
     * 列表展示
     * @param serviceId
     * @param serviceType
     * @return
     */
    @Override
    public List<Map<String, Object>> getQueryFieldCacheConfigByServiceId(String serviceId, String serviceType) {
        List<Map<String, Object>> list = new ArrayList<>();
        List<BaseQueryfieldcacheExt> fielgGroup = queryCacheFieldGroup(serviceId, serviceType);
        if(fielgGroup == null || fielgGroup.isEmpty())
            return list;
        for (BaseQueryfieldcacheExt group : fielgGroup) {
            Map<String, Object> groupMap = new HashMap<>();
            groupMap.put("serviceid", serviceId);
            groupMap.put("servicetype", serviceType);
            groupMap.put("parametergroup", group.getParametergroup());
            List<BaseQueryfieldcacheExt> parmeterlist = queryCacheFieldByServiceIdGroupId(serviceId, serviceType, group.getParametergroup());
            for (BaseQueryfieldcacheExt parmeter : parmeterlist) {
                groupMap.put(parmeter.getParametercode(), parmeter.getParametervalue());
            }
            list.add(groupMap);
        }
        return list;
    }

    @Override
    public Map<String, Object> updateImportFieldCacheInfo(String pcode, String serviceId, String serviceType, List<Map<String, Object>> list) {
        if(list == null || list.isEmpty())
            return setResutl(false, "Excel配置信息为空！", null);
        int size = 0;
        List<BaseQueryfieldcache> fieldcachelist = new ArrayList<>();
        Set<String> groupSet = new HashSet<>();
        for (Map<String, Object> parammap : list) {
            String paramgroup = UUID.randomUUID().toString();
            groupSet.add(paramgroup);
            for (String code : parammap.keySet()) {
                BaseQueryfield baseQueryfield = extBaseQueryfieldMapper.getBaseQueryFieldByServiceIdParmeterCode(serviceId, code);
                if (baseQueryfield == null)
                    return setResutl(false, "Excel配置参数列"+code+"异常！", null);
                BaseQueryfieldcache  fieldcache = new BaseQueryfieldcache();
                fieldcache.setGuid(UUID.randomUUID().toString());
                fieldcache.setFieldaddonsguid(baseQueryfield.getGuid());
                fieldcache.setParametergroup(paramgroup);
                String value = parammap.get(code).toString();
                String reg = "^\\w+\\([\\s\\S]*\\)";
                Pattern p = Pattern.compile(reg);
                Matcher m = p.matcher(value);
                //不符合函数格式当做自定义处理
                if(!m.matches()) {
                    fieldcache.setParametervalue(value);
                    fieldcache.setParameterconfig("customDefind");
                }else{
                    SysFunctionExt sysfunc = getSysFunctionInfoByFuncName(pcode, value.replace(" ", ""));
                    if(sysfunc == null)
                        return setResutl(false, "Excel配置参数列" + code + "值" + value + "异常！", null);
                    fieldcache.setParametervalue(value);
                    fieldcache.setParameterconfig(sysfunc.getGuid());
                }
                fieldcachelist.add(fieldcache);
            }
        }
        for (BaseQueryfieldcache queryField : fieldcachelist) {
            size += baseQueryfieldcacheMapper.insertSelective(queryField);
        }
        if(size <= 0)
            return setResutl(false, "缓存配置导入数据异常！", null);

        return setResutl(true, "缓存配置导入成功！", groupSet);
    }

    /**
     * 返回上传参数结果
     * @param result
     * @param message
     * @param object
     * @return
     */
    private Map<String, Object> setResutl(boolean result, String message, Object object) {
        Map<String, Object> map = new HashMap<>();
        map.put("result", result);
        map.put("message", message);
        map.put("quartz", object);
        return map;
    }

    /**
     * 根据项目和方法匹配函数信息
     * @param pcode
     * @param funcname
     * @return
     */
    private SysFunctionExt getSysFunctionInfoByFuncName(String pcode, String funcname){
        List<SysFunctionExt> list = extSysFunctionMapper.getSysFunctionByPcode(pcode);
        for(SysFunctionExt func: list) {
            funcname = StringUtils.substringBefore(funcname, "(").trim();
            String methodname = StringUtils.substringBetween(func.getFuncscript(),"function", "(").trim();
            if(funcname.equals(methodname)) {
                return func;
            }
        }
        return null;
    }
}
